;

/*
  *
  *
  *下拉建议框
  * by freethy
  * 20161207
  *
  * */

(function($){

    //获取数据
    function getData($panel,$input,options,callback){
        
        var url="";
        if(typeof options.queryParams == "undefined"){
            url = options.url + $input.val();
        } else {
            var param = options.queryParams({});
            param = $.param(param);
            url = options.url + "?" + param + "&key=" +$input.val();
        }
        $.ajax({
            url:url,
            type:'get',
            dataType:'json',
            success:function(data,textStatus,jqXHR){
                //console.log(data);
                callback($panel,$input,data,options);
            }
        });
    }

    //数据加入界面
    function appendRow($panel,$input,data,options){
        options.data = data;
        var html = "";
        for(var i=0;i<data.length;i++){
            if(typeof ($input.attr('date-input')) != 'undefined'){
                if(typeof options.isEvents == "undefined"){
                    html +="<tr data-id='"+data[i][options.idField]+"' data-number='"+data[i][options.numberField]+"'>";
                }else{
                    html +="<tr data-id='"+data[i][options.idField]+"' onclick='"+options.isEvents+"(data[i][options.isEvents])' data-number='"+data[i][options.numberField]+"'>";
                }
            }else{
                if(typeof options.isEvents == "undefined")
                {
                    html +="<tr data-id='"+data[i][options.idField]+"'>";

                }else
                {
                    html +="<tr onclick='"+options.isEvents+"(\""+data[i][options.isEvents]+"\")' data-id='"+data[i][options.idField]+"' >";

                }

            }
            for(var j=0;j<options.columns.length;j++){
                html +="<td>";
                var val = data[i][options.columns[j].field];
                if(val) {

                        html += val;
                    // }else{
                    //     html += "<span style='display: block' onclick='"+options.isEvents+"(\""+val+"\")'>";
                    //     html += val;
                    //     html += "</span>";
                    // }
                }
                html +="</td>";
            }
            html +="</tr>";
        }
        if(html == ""){
            html = "<tr><td colspan='"+options.columns.length+"' style='text-align: center'>No Data</td></tr>";
            $input.addClass("norecord");
        } else {
            $input.removeClass("norecord");
        }
        $panel.find("table tbody").html(html);
    }

    //获取指定id数据
    function getRow(options,id){
        for(var i=0;i<options.data.length;i++){
            if(options.data[i][options.idField] == id){
                return options.data[i];
            }
        }
        return null;
    }

    //设置面板位置
    function setPosition($panel,$input,option){
        var pos = $input.offset();
        var width = $input.outerWidth();
        var height = $input.outerHeight();
        $panel.css("left",pos.left + "px");
        $panel.css("min-width",width+"px");
        if(typeof ($input.attr('date-input')) != 'undefined'){
            $panel.css("max-width",width+"px");
        }
        if(option.width){
            $panel.css("width",option.width+"px");
        }

        if(option.dir && option.dir == 'top'){
            var bot = $("body").height() - pos.top;
            $panel.css("bottom",(bot + 1) + "px");
        } else {
            $panel.css("top",(pos.top + height) + "px");
        }

    }

    var methods = {
        init:function(options){
            //console.log("init");
            //console.log(options);

            var $input = $(this);
            var $onPanel = false;

            //添加表格容器
            var $dropPanel = $("<div class='fSuggest'><table class='table table-hover table-striped' style='table-layout: auto'><thead></thead><tbody></tbody></table></div>");

            //添加表头
            var html = "<tr>";
            for(var i=0;i<options.columns.length;i++){
                html += "<th>";
                html += options.columns[i].title;
                html += "</th>";
            }
            html += "</tr>";
            $dropPanel.find("thead").html(html);

            //添加到页面
            $("body").append($dropPanel);

            //面板事件处理
            $dropPanel.on("mouseenter","tbody",function(){
                $onPanel = true;
                //console.log("mouseenter");
            }).on("mouseleave","tbody",function(){
                $onPanel = false;
                //console.log("mouseleave");
            }).on("mouseover","tbody tr",function(){
                $(this).addClass("hover");
            }).on("mouseout","tbody tr",function(){
                $(this).removeClass("hover");
            }).on("click","tbody td",function(){
                //console.log("tbody td click");
                var id = $(this).parent().attr("data-id");
                var row = getRow(options,id);
                var txt = row[options.textField];

                //console.log(row);
                //console.log(txt);

                $input.attr("data-id",id);
                if(typeof ($input.attr('date-input')) != 'undefined'){
                    var number = $(this).parent().attr("data-number");
                    $input.attr("data-number",number);
                }
                $input.data("id",id);
                $input.val(txt);

                $input.trigger("onSelect",[id,txt,row,options.data]);

                $dropPanel.hide();
                $input.trigger("onHide");

                $input.change();

            });

            //文本框事件处理
            $input.on("click",function(){
                // console.log("input click");

                setPosition($dropPanel,$input,options);
                if($dropPanel.is(':hidden')){
                    $dropPanel.show();
                }

                getData($dropPanel,$input,options,appendRow);

            }).on("blur",function(){
                //console.log("input blur");

                if(!$onPanel){
                    $dropPanel.hide();
                    $input.trigger("onHide");
                }

            }).on("input",function(){
                //console.log("input input");

                if($dropPanel.is(':hidden')){
                    $dropPanel.show();
                    setPosition($dropPanel,$input,options);
                }

                $input.attr("data-id","");
                $input.data("id","");
                $input.trigger("onUnSelect");

                getData($dropPanel,$input,options,appendRow);

            }).on("keydown",function(event){
                //console.log("input keydown " + event);

                if (event.keyCode === 40) {
                    //console.log("input down");

                    if($dropPanel.is(':hidden')){
                        $dropPanel.show();
                        setPosition($dropPanel,$input,options);
                        return false;
                    }

                    var hover = $dropPanel.find("table tbody tr.hover");
                    if(hover.length == 0){
                        $dropPanel.find("table tbody tr:first").trigger('mouseover');
                    } else {
                        hover.trigger('mouseout');
                        hover = hover.next();
                        if(hover.length > 0) {
                            hover.trigger('mouseover');
                        }
                    }

                    return false;
                } else  if (event.keyCode === 38) {
                    //console.log("input up");

                    if($dropPanel.is(':hidden')){
                        $dropPanel.show();
                        setPosition($dropPanel,$input,options);
                        return false;
                    }

                    var hover = $dropPanel.find("table tbody tr.hover");
                    if(hover.length == 0){
                        $dropPanel.find("table tbody tr:last").trigger('mouseover');
                    } else {
                        hover.trigger('mouseout');
                        hover = hover.prev();
                        if(hover.length > 0) {
                            hover.trigger('mouseover');
                        }
                    }

                    return false;
                } else  if (event.keyCode === 13) {
                    //console.log("input enter");

                    if($dropPanel.is(':hidden')){
                        $dropPanel.show();
                        setPosition($dropPanel,$input,options);
                        return false;
                    }

                    var hover = $dropPanel.find("table tbody tr.hover");
                    if(hover.length > 0){
                        var id = hover.attr("data-id");
                        var row = getRow(options,id);
                        var txt = row[options.textField];

                        // console.log(id);
                        // console.log(row);
                        // console.log(txt);

                        $input.attr("data-id",id);
                        $input.data("id",id);
                        $input.val(txt);

                        $input.trigger("onSelect",[id,txt,row,options.data]);

                        $dropPanel.hide();
                            $input.trigger("onHide");
                    }
                } else if (event.keyCode == 27){
                    $dropPanel.hide();
                    $input.trigger("onHide");
                } else{
                    //其他按键不处理
                }
            });

            return this;
            //end init
        },
        show:function(){},
        hide:function(){}
    };

    $.fn.fSuggest = function(options){
        if (typeof options === 'string' && methods[options]) {
            console.log("调用方法");
        } else if (typeof options === 'object' || !options) {
            // 调用初始化方法
            return methods.init.apply(this, arguments);
        }else {

        }
    }

})($);

